import os
from typing import Callable, Iterator, Mapping

from jobs_agency.basics import DetachedJob, JobsAgency, JobsStore, Platform
from .files_store import FilesJobsStore


class MultiplatformJobsAgency(JobsAgency):
    def __init__(self,
        work_dir_path: os.PathLike | str,
        platforms_factory: dict[str, Callable[[JobsStore], Platform]]
    ):
        self._work_dir_path = work_dir_path
        self._platforms = {
            platform_name: platform_factory(FilesJobsStore(os.path.join(work_dir_path, platform_name)))
            for platform_name, platform_factory in platforms_factory.items()}

    @property
    def platforms(self) -> Mapping[str, Platform]:
        return self._platforms

    def get_detached_job(self, job_id: str) -> DetachedJob | None:
        for platform in self._platforms.values():
            job = platform.get_detached_job(job_id)
            if job is not None:
                return job
        return None

    def iter_detached_jobs(self) -> Iterator[DetachedJob]:
        for platform in self._platforms.values():
            yield from platform.iter_detached_jobs()
